<template>
  <div>
    <!-- 搜索区域 -->
    <div class="padding20 whiteBg br-8">
      <el-row class="search_block">
        <el-col :span="8">
          <span class="label_text">编号：</span>
          <el-input
            v-model="searchParams.code"
            clearable
            placeholder="请输入编号"
            style="width: calc(100% - 90px)"
            maxlength="20"
          >
          </el-input>
        </el-col>
        <el-col :span="8">
          <span class="label_text">名称：</span>
          <el-input
            v-model="searchParams.name"
            clearable
            placeholder="请输入名称"
            style="width: calc(100% - 90px)"
            maxlength="20"
          >
          </el-input>
        </el-col>
        <el-col :span="8">
          <span class="label_text">所属类别：</span>
          <el-select
            v-model="searchParams.categoryCode"
            filterable
            clearable
            placeholder="请选择"
            style="width: calc(100% - 90px)"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span class="select-option-code">{{ item.code }}</span>
              <span class="select-option-name">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="8" class="m-t-10">
          <span class="label_text">控制类别：</span>
          <el-select
            v-model="searchParams.controlType"
            filterable
            clearable
            placeholder="请选择"
            style="width: calc(100% - 90px)"
          >
            <el-option label="全部" value=""> </el-option>
            <el-option label="大类" value="1"> </el-option>
            <el-option label="中类" value="2"> </el-option>
            <el-option label="品类" value="3"> </el-option>
            <el-option label="商品" value="4"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="8" class="m-t-10">
          <span class="label_text">状态：</span>
          <el-select
            v-model="searchParams.status"
            filterable
            clearable
            placeholder="请选择"
            style="width: calc(100% - 90px)"
          >
            <el-option label="全部" value="" />
            <el-option label="已生效" value="1" />
            <el-option label="已停用" value="0" />
          </el-select>
        </el-col>
        <el-col :span="8" class="m-t-10">
          <div class="flex_item right" style="margin-right: 5px">
            <el-button @click="handleReset">清空</el-button>
            <el-button type="primary" @click="handleQuery">查询</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格操作区和表格 -->
    <div class="m-t-16 whiteBg padding20 br-8">
      <div class="table_operation" style="margin-bottom: 16px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button class="btn_plain" type="primary" plain @click="handleExport"
          >导出</el-button
        >
      </div>

      <!-- 数据表格 -->
      <el-table
        class="list_table"
        :data="listData"
        border
        v-loading="pageParam.loading"
        style="width: 100%"
        @sort-change="handleSortChange"
        :header-cell-class-name="handleHeaderCellClass"
      >
        <el-table-column
          prop="propertyCode"
          label="编号"
          width="110"
          fixed="left"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleView(scope.row)"
            >
              {{ scope.row.propertyCode || '--' }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column
          prop="propertyName"
          label="属性名称"
          width="164"
        >
        </el-table-column>

        <el-table-column
          prop="propertyType"
          label="所属类别"
          width="110"
        >
          <template #default="scope">
            {{ getCategoryName(scope.row.propertyType) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="controlCategoryTypeName"
          label="主数据控制类型"
          width="150"
        >
        </el-table-column>

        <el-table-column
          prop="managerName"
          label="业务负责人"
          width="110"
          show-overflow-tooltip
        >
        </el-table-column>

        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <span>{{ getStatusLabel(scope.row) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="desc" label="属性说明" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.desc || '--' }}</template>
        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              @click="handleStatusChange(scope.row)"
              v-if="scope.row.status === 0"
            >
              启用
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleStatusChange(scope.row)"
              v-else
            >
              停用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="m-t-24 align-right">
        <el-pagination
          background
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="Number(pageParam.total)"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { getToken } from '@/utils/auth';
import { downloadFile } from '@/utils/func';
import {
  getPropertyList,
  updatePropertyStatus,
  getSpecificationTypeOptions,
} from '@/api/attributeManagement';

const router = useRouter();
const { proxy } = getCurrentInstance();
const $api = proxy?.$api;

// 搜索参数初始化
const initialSearchParams = {
  code: '',
  name: '',
  categoryCode: '',
  controlType: '',
  status: '',
};

const searchParams = reactive({ ...initialSearchParams });

// 分页参数
const pageParam = reactive({
  loading: false,
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

// 数据和状态
const listData = ref([]);
const categoryList = ref([]);
const sortField = new Map();

/**
 * 查询列表数据
 */
const getListData = async () => {
  pageParam.loading = true;
  try {
    // 构建请求参数
    const params = {
      propertyCode: searchParams.code,
      propertyName: searchParams.name,
      propertyType: searchParams.categoryCode || undefined,
      controlCategoryType: searchParams.controlType || undefined,
      status:
        searchParams.status !== '' ? Number(searchParams.status) : undefined,
      pageNo: pageParam.pageNo,
      pageSize: pageParam.pageSize,
    };

    // 移除 undefined 的参数
    Object.keys(params).forEach(
      (key) => params[key] === undefined && delete params[key]
    );

    // 调用 API 获取属性列表
    const res = await getPropertyList(params, true);

    const rows = Array.isArray(res?.data) ? res.data : [];
    listData.value = rows;

    const pageInfo = res?.page || {};
    pageParam.total = Number(pageInfo.total ?? rows.length ?? 0) || 0;
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取列表失败');
  } finally {
    pageParam.loading = false;
  }
};

/**
 * 查询操作
 */
const handleQuery = () => {
  pageParam.pageNo = 1;
  getListData();
};

/**
 * 重置搜索参数
 */
const handleReset = () => {
  Object.keys(initialSearchParams).forEach((key) => {
    searchParams[key] = initialSearchParams[key];
  });
};

/**
 * 分页大小改变
 */
const handleSizeChange = (val) => {
  pageParam.pageNo = 1;
  pageParam.pageSize = val;
  getListData();
};

/**
 * 当前页改变
 */
const handleCurrentChange = (val) => {
  pageParam.pageNo = val;
  getListData();
};

/**
 * 新增属性
 */
const handleAdd = () => {
  router.push({
    name: 'attributeManagementCreate',
  });
};

/**
 * 查看详情
 */
const handleView = (row) => {
  if (!row?.propertyCode) return;
  router.push({
    name: 'attributeManagementDetail',
    query: {
      propertyCode: row.propertyCode,
    },
  });
};

/**
 * 编辑属性
 */
const handleEdit = (row) => {
  router.push({
    name: 'attributeManagementEdit',
    query: {
      propertyCode: row.propertyCode,
    },
  });
};

/**
 * 启用/停用属性
 */
const handleStatusChange = async (row) => {
  const currentStatus = row.status;
  const action = currentStatus === 1 ? '停用' : '启用';

  try {
    await ElMessageBox.confirm(`确认${action}该属性吗？`, {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    if (!row?.propertyCode) {
      ElMessage.error('缺少属性编号，无法变更状态');
      return;
    }

    // 调用 API 更新状态
    const newStatus = currentStatus === 1 ? 0 : 1;
    const params = {
      propertyCode: row.propertyCode,
      status: newStatus,
    };
    await updatePropertyStatus(params, true);

    ElMessage.success(`${action}成功`);
    getListData();
  } catch (error) {
    console.error(`${action}失败:`, error);
  }
};

/**
 * 导出
 */
const handleExport = async () => {
  try {
    const params = {
      userToken: getToken('token_op_login_key')
        ? getToken('token_op_login_key')
        : undefined,
      propertyCode: searchParams.code || undefined,
      propertyName: searchParams.name || undefined,
      status:
        searchParams.status !== '' ? Number(searchParams.status) : undefined,
      controlCategoryType: searchParams.controlType || undefined,
      propertyType: searchParams.categoryCode || undefined,
    };

    Object.keys(params).forEach(
      (key) => params[key] === undefined && delete params[key]
    );

    const res = await $api.get(
      '/item-center/property/export',
      params,
      false,
      'blob'
    );
    downloadFile(res.data, res.headers);
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败');
  }
};

/**
 * 表头样式处理
 */
const handleHeaderCellClass = (params) => {
  if (sortField.has(params.column.property)) {
    params.column.order = sortField.get(params.column.property);
  }
};

/**
 * 排序改变
 */
const handleSortChange = (params) => {
  if (params.order == null) {
    sortField.delete(params.prop);
  } else {
    sortField.set(params.prop, params.order);
  }
  getListData();
};

/**
 * 获取类别名称
 */
const getCategoryName = (code) => {
  if (!code) return '--';
  const category = categoryList.value.find((item) => item.code === code);
  return category ? category.name : code;
};

/**
 * 状态显示文案：1 -> 已生效，0 -> 已停用
 */
const getStatusLabel = (row) => {
  if (!row) return '--';
  const value = row.status;
  if (value === '' || value === null || value === undefined) return '--';
  const num = Number(value);
  if (Number.isNaN(num)) return '--';
  return num === 1 ? '已生效' : '已停用';
};

/**
 * 获取类别列表
 */
const getCategoryList = async () => {
  try {
    const res = await getSpecificationTypeOptions({}, true);

    // 映射接口返回的数据
    const mappedData = (res.data || []).map((item) => ({
      code: item.code,
      name: item.description,
      extendedField1: item.extendedField1,
    }));

    categoryList.value = mappedData;
  } catch (error) {
    console.error('获取类别列表失败:', error);
  }
};

/**
 * 初始化
 */
const init = async () => {
  await Promise.all([getCategoryList(), getListData()]);
};

onMounted(() => {
  init();
});
</script>

<style lang="less" scoped>
.label_text {
  display: inline-block;
  text-align: right;
  width: 80px;
}
/deep/.el-table th {
  background-color: #e5e5e5 !important;
}

.select-option-code {
  display: inline-block;
  width: 90px;
  color: #606266;
}

.select-option-name {
  display: inline-block;
  width: calc(100% - 90px);
  color: #303133;
  text-align: right;
}
</style>
